@tool
extends TileMap

@export var genTerrain: bool
@export var clearTerrain: bool
@export var mapWidth: int
@export var mapHeight: int
@export var grassThreshold: float
@export var grass2Threshold: float
@export var dirtThreshold: float
@export var rockThreshold: float
@export var terrainSeed: int


# Called when the node enters the scene tree for the first time.
func _ready():
	pass


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	if genTerrain:
		genTerrain = false
		GenerateTerrain()
	if clearTerrain:
		clearTerrain = false
		clear()
	
func GenerateTerrain():
	print("generating terrain...")
	
	var noise = FastNoiseLite.new()
	noise.noise_type = FastNoiseLite.TYPE_CELLULAR
	
	var rng = RandomNumberGenerator.new()
	
	if terrainSeed == 0:
		noise.seed = rng.randi()
	else:
		noise.seed = terrainSeed
	
	for x in range(mapWidth):
		for y in range(mapHeight):
			var val = noise.get_noise_2d(x, y)
			var atlas_coords = Vector2i(0, 1)
			if val > grassThreshold:
				atlas_coords = Vector2i(0,0)
			elif val > grass2Threshold:
				atlas_coords = Vector2i(1,0)
			elif val > dirtThreshold:
				atlas_coords = Vector2i(2,0)
			elif val > rockThreshold:
				atlas_coords = Vector2i(3,0)
			set_cell(0, Vector2i(x, y), 0, atlas_coords)
